<template>
  <l-layout class="l-tab-page erpCase" v-show="!lr_loadPage">
    <l-panel v-show="!pageFormVisible" :title="$t('正式供应商')">
      <template #toolLeft>
        <l-query2
          :items="queryItems"
          :formData="queryData"
          :loading="tableLoading"
          @search="handleSearch"
        >
          <template #f_FormalState>
            <l-select
              v-model="queryData.f_FormalState"
              :options="case_erp_supplier_f_FormalStateOptions"
            />
          </template>
          <template #f_Type>
            <l-select
              v-model="queryData.f_Type"
              :options="case_erp_supplier_f_TypeStateOptions"
            />
          </template>
        </l-query2>
      </template>
      <template #toolRight>
        <l-tool-btns
          :hasTableSetting="true"
          @setting="lr_handleSettingTable"
          :hasAdd="false"
        >
          <!-- <l-excel-btns :moduleCode="moduleCode"></l-excel-btns> -->
        </l-tool-btns>
      </template>

      <l-table
        ref="mainTable"
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableData"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
        :key="tableData.index"
      >
        <template v-slot:f_TypeList="scope">
          <div class="form_information form_wrap">
            <div v-for="(item, index) in scope.row.f_TypeList" :key="index">
              <el-tag size="mini" class="margin_5" :type="tagType[item]">{{
                item
              }}</el-tag>
            </div>
          </div>
        </template>

        <l-table-btns
          :btns="tableBtns"
          :btnNum="6"
          :filterBtns="filterBtns"
          :isAuth="false"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <transition name="el-zoom-in-center">
      <l-panel v-if="pageFormVisible">
        <template #title>
          <el-page-header
            @back="
              () => {
                pageFormVisible = false;
              }
            "
            :content="$t(pageFormname)"
          />
        </template>
        <!-- 供应商详情查看 -->
        <look-form
          v-if="['详情查看'].includes(pageFormname)"
          ref="lookForm"
          :id="formEditRow.f_Id"
          type="0"
        />
        <!-- 供应商年审 -->
        <wf-create-form
          v-else-if="['供应商年审'].includes(pageFormname)"
          ref="wfcreate"
          code="erp-supplier-year"
          wraperType="page"
          wfSubmitText="提交保存"
          :params="{
            id: supplierId,
          }"
          @refresh="wfSubmit"
        />

        <supply-list v-else :supplierId="supplierId" />
      </l-panel>
    </transition>

    <!--表单-->
    <l-dialog
      :title="$t(formTitle)"
      :visible.sync="formVisible"
      :height="426"
      :width="487"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form
        v-if="formTitle != '供应商淘汰设置'"
        ref="form"
      />
      <!-- 淘汰 -->
      <eliminat-form
        v-else
        ref="form"
      />
    </l-dialog>
    

    <wf-audit-form
      ref="form"
      type="auditAndlook"
      :params="{ loadProcessId: loadProcessId }"
      :isLoadFormData="true"
      title="供应商年审"
      :visible.sync="wfvisible"
      @refresh="wfSubmit()"
    />
  </l-layout>
</template>

<script>
const api = window.$api.erpcase.supplier;

import MyForm from "../supplier/form";
import lookForm from "./lookForm";

import SupplyList from "./SupplyList";
import EliminatForm from "./eliminatForm";
export default {
  components: {
    MyForm,
    SupplyList,
    EliminatForm,
    lookForm,
  },
  data() {
    return {
      lr_isPage: true,
      moduleCode: "ERP_FormalSuppliers",
      // 查询参数
      queryData: {
        f_FormalState: "",
        f_Type: "",
      },

      tagType: {
        成品: "danger",
        半成品: "success",
        其他: "info",
        原料: "",
      },

      queryItems: [
        { label: "当前年审", prop: "f_FormalState" },
        { label: "供应商类型", prop: "f_Type" },
      ],

      // 表格参数
      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tableCurrentPage: 1,
      tablePageSize: 50,
      columns: [
        {
          label: "供应商编号",
          prop: "f_Number",
          align: "left",
          dataType: "guid",
          width: 160,
          isNotAutoWrap: true,
        },
        {
          label: "供应商名称",
          prop: "f_Name",
          align: "left",
          dataType: "input",
          minWidth: 160,
          isNotAutoWrap: true,
        },
        {
          label: "供应商负责人",
          prop: "f_Person",
          align: "left",
          width: 100,
        },
        { label: "手机号", prop: "f_Phone", align: "left", width: 120 },
        {
          label: "经营范围",
          prop: "f_Scope",
          align: "left",
          width: 120,
        },
        {
          label: "当前年审",
          prop: "f_FormalState",
          align: "left",
          dataType: "mydata",
          options: [
            { value: 0, label: "未年审" },
            { value: 1, label: "审批中" },
            { label: "不通过", value: 2 },
            { label: "通过", value: 3 },
            { label: "无需年审", value: 4 },
          ],
        },
        {
          label: "供应商类型",
          prop: "f_TypeList",
          align: "left",
          dataType: "dataItem",
          dataCode: "供应商类型",
          width: 220,
        },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑", width: 120 },
        { prop: "Details", label: "详情查看" },
        { prop: "Review", label: "企业年审" },
        { prop: "SupplyList", label: "供货清单" },
        { prop: "Eliminate", label: "淘汰" },
        { prop: "Delete", label: "删除" },
      ],

      // 表单参数
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      pageFormname: "",
      pageFormVisible: false,

      wfvisible: false,
    };
  },
  computed: {
    case_erp_supplier_f_FormalStateOptions() {
      return [
        { label: "全部", value: "" },
        { label: "未年审", value: "0" },
        { label: "审批中", value: "1" },
        { label: "不通过", value: "2" },
        { label: "通过", value: "3" },
        { label: "无需年审", value: "4" },
      ];
    },
    case_erp_supplier_f_TypeStateOptions() {
      return [
        { label: "全部", value: "" },
        { value: "原料", label: "原料" },
        { value: "半成品", label: "半成品" },
        { label: "成品", value: "成品" },
        { label: "其他", value: "其他" },
      ];
    },
    supplierId() {
      return this.formEditRow ? this.formEditRow.f_Id : "";
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.loadTableData();
    },
    wfSubmit() {
      this.pageFormVisible = false;
      this.loadTableData();
    },
    async loadProcessId() {
      const data = await this.$awaitWraper(
        api.getYearBySupplierId(this.supplierId)
      );
      if (data) {
        return data.f_Id;
      }
      return "";
    },

    // 自定义按钮
    filterBtns(row, btns) {
      if (row.f_FormalState == 2 || row.f_FormalState == 3 ) {
        btns[2].label = '年审查看';
      }

      if (row.f_FormalState == 4) {
        btns[2].disabled = true;
      }
      return btns;
    },

    //  供货清单
    handleSupplyList(index, row) {
      this.formEditRow = row;
      this.pageFormname = `供货清单（${row.f_Name}）`;
      this.pageFormVisible = true;
    },
    // 企业年审
    handleReview(index, row) {
      this.formEditRow = row;
      if (row.f_FormalState == 0) {
        this.pageFormname = `供应商年审`;
        this.pageFormVisible = true;
      }
      else{
        this.wfvisible = true;
      }
    },

    handleSearch() {
      this.loadTableData();
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = this.$deepClone(this.queryData);

      queryData.rows = this.tablePageSize;
      queryData.page = this.tableCurrentPage;
      queryData.sidx = "F_Id";
      queryData.f_State = 1;
      let data = await this.$awaitWraper(api.getPage(queryData));
      if (data != null) {
        this.tableData = data.rows;
        for (let i in this.tableData) {
          this.tableData[i].f_TypeList = this.tableData[i].f_Type.split(",");
        }
        this.tableTotal = data.records;
      } else {
        this.tableData = [];
      }
      this.tableLoading = false;
    },

    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm("编辑");
    },
    handleDetails($index, row) {
      this.pageFormname = `详情查看`;
      this.formEditRow = row;
      this.pageFormVisible = true;
    },

    // 淘汰
    handleEliminate($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.handleShowForm("供应商淘汰设置");
    },

    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(async () => {
          this.tableData.splice($index, 1);
          this.tableTotal--;
          await api.remove(row.f_Id);
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除!"),
          });
        });
    },

    async handleSave(showLoading, hideLoading) {
      showLoading("保存数据中...");
      if ((await this.$refs.form.validateForm())) {
        const res = await this.$refs.form.saveForm({
          keyValue: this.formEdit ? this.formEditRow.f_Id : "",
          isEdit: this.formEdit,
        });
        if (res) {
          const msg = this.formEdit ? "更新成功!" : "新增成功!";
          this.$message({
            type: "success",
            message: this.$t(msg),
          });
          this.loadTableData();
          this.formVisible = false;
        }
      }
      hideLoading();
    },

    handleShowForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    async handleOpenedForm(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.$refs.form.loadFormData({ keyValue: this.formEditRow.f_Id });
        hideLoading();
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
  },
};
</script>
<style>
.div_title {
  font-size: 16px;
  font-weight: normal;
  color: #444444;
  padding-left: 20px;
}
</style>